import React from 'react';
import { Input, message, Modal } from 'antd';
import { Form, Icon } from '@ant-design/compatible';
import { connect } from 'dva';
import { pageSize, apiUrl, modalWidth } from '../../../config';
import { IconButton, PageHeaderLayout, StandardTable, SearchForm, PageCard } from '../../components';
import styles from './resource.css';

const reqApi = 'resource';
const formItemLayout = {
  labelCol: { md: 3 },
  wrapperCol: { md: 21 },
};
const moduleValue = [
  ['api', 'api'],
  ['basic', 'basic'],
  ['info', 'info'],
  ['student', 'student'],
];

class page extends React.Component {
  state = {
    loading: true,
    dialogLoading: false,
    visible: false,
    dialogTitle: '',
    searchs: [],
    pagination: {
      current: 1,
      pageSize,
      onShowSizeChange: (_, size) => {
        const { pagination } = this.state;
        pagination.pageSize = size;
      },
    },
    remark: '', // 接口说明
  };

  componentDidMount() {
    this.funcGetListData();
  }

  // 表格列
  columns = [
    {
      title: '所属模块',
      dataIndex: 'moduleId',
      type: 'select',
      sub: moduleValue,
      width: 100,
    },
    {
      title: '接口名称',
      dataIndex: 'name',
    },
    {
      title: '接口路径',
      dataIndex: 'resUrl',
      type: 'text',
      render: (text, record) => (
        <a
          className={styles.link}
          onClick={() => this.funcOpenForm(record)}
        >
          {text}
        </a>
      ),
    },
  ];

  // 读取表记录
  funcGetListData = () => {
    this.setState({
      loading: true,
    });

    const { state } = this;
    const { searchs, pagination } = state;
    const { current, pageSize } = pagination;
    const { dispatch } = this.props;

    dispatch({
      type: reqApi + '/list',
      payload: {
        currentPage: current,
        pageSize,
        searchs,
      },
    }).then(() => this.setState({ loading: false }));
  };

  // 记录查询表单提交
  funcOnSubmitSearch = (searchs) => {
    const { state } = this;
    state.pagination.current = 1;
    this.setState({ searchs }, this.funcGetListData);
  };

  // 弹出表单
  funcOpenForm = (record) => {
    const { name, resUrl, remark, params } = record;
    let newParams = params;
    try {
      const obj = JSON.parse(params);
      newParams = JSON.stringify(obj, null, 2);
    } catch (error) {
      console.log(error);
    }

    this.setState({
      visible: true,
      dialogTitle: name,
      remark,
    }, () => {
      const { form } = this.props;
      form.resetFields();
      form.setFieldsValue({
        resUrl: apiUrl() + '/' + resUrl,
        params: newParams,
      });
    });
  };

  // 提交测试
  funcSubmit = () => {
    const { form, dispatch } = this.props;
    form.validateFields((error, values) => {
      if (error) return error;

      try {
        JSON.parse(values.params);
      } catch (e) {
        message.error('请求参数json格式有误，请检查！');
        return;
      }

      form.setFieldsValue({ result: '' });
      this.setState({ dialogLoading: true });

      dispatch({
        type: reqApi + '/anyReq',
        payload: JSON.parse(values.params),
        url: values.resUrl,
      }).then(() => {
        const { props } = this;
        const { result } = props[reqApi];
        let newResult = result;
        try {
          newResult = JSON.stringify(result, null, 2);
        } catch (error) {
          console.log(error);
        }
        form.setFieldsValue({ result: newResult });
        this.setState({ dialogLoading: false });
      });
    });
  };

  render() {
    const { state, props } = this;
    const { getFieldDecorator } = props.form;

    return (
      <PageHeaderLayout title={props.route.name}>
        <PageCard
          children={(
            <div>
              <SearchForm fields={this.columns} onSubmit={this.funcOnSubmitSearch} />
              <StandardTable
                columns={this.columns}
                loading={state.loading}
                data={{
                  list: props[reqApi].data,
                  pagination: { ...state.pagination, total: props[reqApi].total },
                }}
                onChange={(pageParams) => {
                  const { pagination } = this.state;
                  pagination.current = pageParams.current;
                  this.funcGetListData();
                }}
                scrollX={576}
              />
            </div>
          )}
        />

        <Modal
          width={modalWidth}
          title={(
            <div>
              <Icon type="api" style={{ fontSize: 16, marginRight: 8 }} />
              <span>接口测试：{state.dialogTitle}</span>
            </div>
          )}
          visible={state.visible}
          onOk={this.funcSubmit}
          onCancel={() => this.setState({ visible: false })}
          footer={[
            <IconButton key="cancel" text='关闭' type='default' onClick={() => this.setState({ visible: false })} />,
            <IconButton
              key="ok"
              text='测试'
              icon='fork'
              loading={state.dialogLoading}
              onClick={this.funcSubmit}
            />,
          ]}
          bodyStyle={{ paddingBottom: 0 }}
        >
          <Form>
            <Form.Item label="接口地址" {...formItemLayout}>
              {getFieldDecorator('resUrl', {
                rules: [{ required: true, message: '请输入网络请求的接口地址' }],
              })(<Input maxLength={255} />)}
            </Form.Item>

            {state.remark ? (
              <Form.Item label="接口说明" {...formItemLayout}>
                <div className={styles.blockquote}>
                  {state.remark}
                </div>
              </Form.Item>
            ) : null}

            <Form.Item label="请求参数" {...formItemLayout}>
              {getFieldDecorator('params', {
                rules: [{ required: true, message: '请输入json格式的参数' }],
              })(
                <Input.TextArea autoFocus rows={5} />
              )}
            </Form.Item>

            <Form.Item label="返回结果" {...formItemLayout}>
              {getFieldDecorator('result')(
                <Input.TextArea readOnly className={styles.code} rows={5} />
              )}
            </Form.Item>
          </Form>
        </Modal>
      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ resource, menu }) => ({ resource, menu }))(page2);
